# -*- coding: utf-8 -*-
'''
Created on Dec 7, 2013

@author: LONG HOANG GIANG
'''

from urlparse import urljoin
from collections import OrderedDict
import lib

def exportDetail(result):
    data = []
    
    for k, v in result.items():
        if k == 'ev':
            text = '<h4 class="dic_type">Từ điển Anh - Việt</h4>'
        elif k == 'cn':
            text = '<h4>Từ điển chuyên ngành</h4>'
        text += v
        data.append(text)
    
    html =  "<div>" + '<hr class="separate"/>'.join(data) + "</div>"
    node = lib.Etree.fromstring(html)
    lib.Etree.strip_tags(node, 'font', 'a')
    html = lib.Etree.tostring(node)
    return html
    
def getDetail(url):
    
    tree = lib.Web.load(url).build_tree()
    xpathLst = OrderedDict([('ev', 'mtd_0'), ('cn', 'mtd_1')])
    means = OrderedDict()
    for dtype, xpath in xpathLst.items():
        contentNode = tree.xpath("//div[@id='ctl00_ContentPlaceHolderMain_ctl00' and @class='kq']//div[@id='{0}']/div[2]/div[@class='p10']".format(xpath))[0]
        html = lib.Etree.tostring(contentNode)
        means[dtype] = html
        
    data = exportDetail(means)

    lib.file_put_content(data, "F:/aaa.html")
    
    
def getAllWords():
    
    urlfm = 'http://tratu.vietgle.vn/hoc-tieng-anh/tu-thong-dung/vietgle-tra-tu/tat-ca/trang-{0}.html'
    for page in range(1, 74):
        url = urlfm.format(page)
        tree = lib.Web.load(url).build_tree()
        
        for item in tree.xpath("//div[@class='p5b fl']"):
            
            wNode = item.xpath(".//div[@class='itron lb fl m10l']/a")[0]
            word = lib.stringify(wNode)
            link = urljoin(url, wNode.get('href'))
            phoneticNode = item.xpath(".//div[@class='itron lb fl m10l']/span[@class='nb cB']")[0]
            phonetic = lib.stringify(phoneticNode)
            
            
            print word, phonetic, link
            
getDetail('http://tratu.vietgle.vn/hoc-tieng-anh/chi-tiet-tu-dien/all/control.html')